<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="主体名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入主体名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册手机号" prop="mobilePhone">
        <el-input
          v-model="queryParams.mobilePhone"
          placeholder="请输入注册手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="registerTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否有营业执照" prop="hasBusinessLicense">
        <el-select v-model="queryParams.hasBusinessLicense" placeholder="请选择是否有营业执照" clearable>
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <!-- 管理员显示省市区查询条件 -->
      <template v-if="isAdmin">
        <el-form-item label="省" prop="province">
          <el-select v-model="queryParams.province" placeholder="请选择省" clearable @change="handleProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.value"
              :label="province.label"
              :value="province.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="queryParams.city" placeholder="请选择市(请先选择省)" clearable @change="handleCityChange">
            <el-option
              v-for="city in cityOptions"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select v-model="queryParams.district" placeholder="请选择区/县(请先选择市)" clearable>
            <el-option
              v-for="district in districtOptions"
              :key="district.value"
              :label="district.label"
              :value="district.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <!-- 监管者只显示乡镇/街道查询条件 -->
      <el-form-item label="乡镇/街道" prop="township">
        <el-select v-model="queryParams.township" placeholder="请选择乡镇/街道" clearable>
          <el-option
            v-for="township in townshipOptions"
            :key="township.value"
            :label="township.label"
            :value="township.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主体类型" prop="entityType">
        <el-select v-model="queryParams.entityType" placeholder="请选择主体类型" clearable>
          <el-option label="企业" value="enterprise" />
          <el-option label="合作社" value="cooperative" />
          <el-option label="家庭农场" value="family_farm" />
          <el-option label="个体户" value="individual" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="法人名称" prop="legalPersonName">
        <el-input
          v-model="queryParams.legalPersonName"
          placeholder="请输入法人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:memberDetailInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:memberDetailInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberDetailInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="注册手机号" align="center" prop="mobilePhone" width="130" />
      <el-table-column label="是否有营业执照" align="center" prop="hasBusinessLicense" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hasBusinessLicense == '1'" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主体名称" align="center" prop="companyName" width="200" show-overflow-tooltip />
      <el-table-column label="法人名称" align="center" prop="legalPersonName" width="120" />
      <el-table-column label="统一社会信用代码" align="center" prop="socialCreditCode" width="180" show-overflow-tooltip />
      <el-table-column label="证件号码" align="center" prop="idNumber" width="180" show-overflow-tooltip />
      <el-table-column label="注册资金(万元)" align="center" prop="registeredCapital" width="120" />
      <el-table-column label="企业成立时间" align="center" prop="establishmentDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.establishmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="registerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="130" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nongjt:memberDetailInfo:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleAudit(scope.row)"
            v-hasPermi="['nongjt:memberDetailInfo:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPassword(scope.row)"
            v-hasPermi="['nongjt:memberDetailInfo:resetPassword']"
          >重置密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nongjt:memberDetailInfo:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleMore(scope.row)"
          >更多</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员详细信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="注册手机号" prop="mobilePhone">
              <el-input v-model="form.mobilePhone" placeholder="请输入注册手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间" prop="registerTime">
              <el-date-picker clearable
                v-model="form.registerTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择注册时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入主体名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人姓名" prop="legalPersonName">
              <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="省" prop="province">
              <el-select v-model="form.province" placeholder="请选择省" @change="handleProvinceChange">
                <el-option
                  v-for="province in provinceOptions"
                  :key="province.value"
                  :label="province.label"
                  :value="province.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市" prop="city">
              <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange">
                <el-option
                  v-for="city in cityOptions"
                  :key="city.value"
                  :label="city.label"
                  :value="city.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区/县" prop="district">
              <el-select v-model="form.district" placeholder="请选择区/县">
                <el-option
                  v-for="district in districtOptions"
                  :key="district.value"
                  :label="district.label"
                  :value="district.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="乡镇/街道" prop="township">
              <el-select v-model="form.township" placeholder="请选择乡镇/街道">
                <el-option
                  v-for="township in townshipOptions"
                  :key="township.value"
                  :label="township.label"
                  :value="township.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="detailedAddress">
              <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="socialCreditCode">
              <el-input v-model="form.socialCreditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资金(万元)" prop="registeredCapital">
              <el-input-number v-model="form.registeredCapital" :precision="2" :step="0.01" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业成立时间" prop="establishmentDate">
              <el-date-picker clearable
                v-model="form.establishmentDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择企业成立时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-input v-model="form.industry" placeholder="请输入所属行业" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体类型" prop="entityType">
              <el-select v-model="form.entityType" placeholder="请选择主体类型">
                <el-option label="企业" value="enterprise" />
                <el-option label="合作社" value="cooperative" />
                <el-option label="家庭农场" value="family_farm" />
                <el-option label="个体户" value="individual" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产类型" prop="productionType">
              <el-input v-model="form.productionType" placeholder="请输入生产类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有营业执照" prop="hasBusinessLicense">
              <el-radio-group v-model="form.hasBusinessLicense">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否打印合格证抬头" prop="printCertificateHeader">
              <el-radio-group v-model="form.printCertificateHeader">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="认证资质" prop="certificationQualification">
          <el-input v-model="form.certificationQualification" type="textarea" placeholder="请输入认证资质" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核" :visible.sync="auditOpen" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio label="0">待审核</el-radio>
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="auditRemark">
          <el-input v-model="auditForm.auditRemark" type="textarea" placeholder="审核不通过时必须填写不通过原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重新设定密码" :visible.sync="passwordOpen" width="500px" append-to-body>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="登陆账号" prop="mobilePhone">
          <el-input v-model="passwordForm.mobilePhone" disabled />
        </el-form-item>
        <el-form-item label="登陆密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPassword">确 定</el-button>
        <el-button @click="cancelPassword">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMemberDetailInfo, getMemberDetailInfo, delMemberDetailInfo, addMemberDetailInfo, updateMemberDetailInfo, auditMemberDetailInfo, resetPassword } from "@/api/monitor/njt/member/detailInfo";

export default {
  name: "MemberDetailInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员详细信息表格数据
      memberDetailInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示审核弹出层
      auditOpen: false,
      // 是否显示密码重置弹出层
      passwordOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        mobilePhone: null,
        registerTime: null,
        hasBusinessLicense: null,
        province: null,
        city: null,
        district: null,
        township: null,
        entityType: null,
        contactPhone: null,
        legalPersonName: null
      },
      // 表单参数
      form: {},
      // 审核表单参数
      auditForm: {},
      // 密码重置表单参数
      passwordForm: {},
      // 表单校验
      rules: {
        mobilePhone: [
          { required: true, message: "注册手机号不能为空", trigger: "blur" }
        ],
        companyName: [
          { required: true, message: "主体名称不能为空", trigger: "blur" }
        ],
        legalPersonName: [
          { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        province: [
          { required: true, message: "省不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "市不能为空", trigger: "change" }
        ],
        district: [
          { required: true, message: "区/县不能为空", trigger: "change" }
        ],
        township: [
          { required: true, message: "乡镇/街道不能为空", trigger: "change" }
        ]
      },
      // 审核表单校验
      auditRules: {
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ],
        auditRemark: [
          { validator: this.validateAuditRemark, trigger: "blur" }
        ]
      },
      // 密码重置表单校验
      passwordRules: {
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
        ]
      },
      // 省市区选项
      provinceOptions: [
        { label: '四川省', value: '四川省' }
      ],
      cityOptions: [],
      districtOptions: [],
      townshipOptions: [],
      // 是否为管理员
      isAdmin: true
    };
  },
  created() {
    this.getList();
    this.initRegionData();
  },
  methods: {
    /** 查询会员详细信息列表 */
    getList() {
      this.loading = true;
      listMemberDetailInfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.memberDetailInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        mobilePhone: null,
        registerTime: null,
        companyName: null,
        legalPersonName: null,
        idNumber: null,
        contactPhone: null,
        province: null,
        city: null,
        district: null,
        township: null,
        detailedAddress: null,
        socialCreditCode: null,
        registeredCapital: null,
        establishmentDate: null,
        industry: null,
        entityType: null,
        productionType: null,
        hasBusinessLicense: null,
        businessLicensePhoto: null,
        certificationQualification: null,
        brandLogo: null,
        photoWall: null,
        auditStatus: null,
        auditTime: null,
        auditRemark: null,
        printCertificateHeader: null,
        perfectTime: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员详细信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMemberDetailInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员详细信息";
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.auditForm = {
        id: row.id,
        auditStatus: row.auditStatus || '0',
        auditRemark: row.auditRemark || ''
      };
      this.auditOpen = true;
    },
    /** 重置密码按钮操作 */
    handleResetPassword(row) {
      this.passwordForm = {
        userId: row.userId,
        mobilePhone: row.mobilePhone,
        newPassword: '123456'
      };
      this.passwordOpen = true;
    },
    /** 更多按钮操作 */
    handleMore(row) {
      // 实现更多操作逻辑
      this.$message.info("更多功能开发中...");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMemberDetailInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMemberDetailInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          auditMemberDetailInfo(this.auditForm).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 提交密码重置 */
    submitPassword() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          resetPassword(this.passwordForm).then(response => {
            this.$modal.msgSuccess("密码重置成功");
            this.passwordOpen = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const message = row.id ? '是否确认删除该会员详细信息？' : '是否确认删除选中的会员详细信息？';
      this.$modal.confirm(message).then(function() {
        return delMemberDetailInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/memberDetailInfo/export', {
        ...this.queryParams
      }, `会员详细信息_${new Date().getTime()}.xlsx`)
    },
    // 取消审核
    cancelAudit() {
      this.auditOpen = false;
      this.auditForm = {};
    },
    // 取消密码重置
    cancelPassword() {
      this.passwordOpen = false;
      this.passwordForm = {};
    },
    // 审核备注校验
    validateAuditRemark(rule, value, callback) {
      if (this.auditForm.auditStatus === '2' && (!value || value.trim() === '')) {
        callback(new Error('审核不通过时必须填写不通过原因'));
      } else {
        callback();
      }
    },
    // 初始化地区数据
    initRegionData() {
      // 这里应该从后端获取地区数据，暂时使用模拟数据
      this.cityOptions = [
        { label: '成都市', value: '成都市' }
      ];
      this.districtOptions = [
        { label: '郫都区', value: '郫都区' },
        { label: '新都区', value: '新都区' },
        { label: '温江区', value: '温江区' }
      ];
      this.townshipOptions = [
        { label: '郫筒街道', value: '郫筒街道' },
        { label: '安德街道', value: '安德街道' },
        { label: '新桥街道', value: '新桥街道' },
        { label: '德源街道', value: '德源街道' }
      ];
    },
    // 省变化处理
    handleProvinceChange(value) {
      this.queryParams.city = null;
      this.queryParams.district = null;
      this.form.city = null;
      this.form.district = null;
      // 根据省加载市数据
    },
    // 市变化处理
    handleCityChange(value) {
      this.queryParams.district = null;
      this.form.district = null;
      // 根据市加载区县数据
    }
  }
};
</script>
